<?php

namespace App\Model\Common;
use Illuminate\Support\Facades\DB;

class ProjectHistory extends Common
{
    public function edit($data, $opt = [])
    {
        DB::beginTransaction();
        try {
            $len = !empty($data['history_intro']) ? count($data['history_intro']) : 0;
            $len_id = !empty($data['history_id']) ? count($data['history_id']) : 0;

            $old_history = [];
            for ($i = 0; $i < $len_id; ++$i) {
                $old_history[$i]['id'] = $data['history_id'][$i];
                $old_history[$i]['intro'] = $data['history_intro'][$i];
                $old_history[$i]['date'] = $data['history_date'][$i];
                $description = str_replace('<br />', '', $data['history_description'][$i]);
                $old_history[$i]['description'] = nl2br($description);
            }
            foreach ($old_history as $history) {
                $this->where('id', $history['id'])->where('project_id', $data['project_id'])->update($history);
            }
            if ($len - $len_id > 0) {
                $new_history = [];
                for ($i = $len_id; $i < $len; ++$i) {
                    $new_history[$i]['intro'] = $data['history_intro'][$i];
                    $new_history[$i]['date'] = $data['history_date'][$i];
                    $new_history[$i]['description'] = nl2br($data['history_description'][$i]);
                    $new_history[$i]['project_id'] = $data['project_id'];
                }
                $this->insert($new_history);
            }

            DB::commit();
        } catch (\Illuminate\Database\QueryException $e) {
            DB::rollBack();
            $this->error = $e->errorInfo[2];

            return false;
        }
        return true;
    }
}
